package com.yserp.project.erp.order.productbom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yserp.common.exception.BusinessException;
import com.yserp.common.utils.StringUtils;
import com.yserp.common.utils.bean.BeanUtils;
import com.yserp.common.utils.mybatis.MybatisPlusUtil;
import com.yserp.common.utils.text.Convert;
import com.yserp.project.erp.common.enums.OrderEnums;
import com.yserp.project.erp.order.productbom.domain.ProductionBom;
import com.yserp.project.erp.order.productbom.domain.ProductionBomDto;
import com.yserp.project.erp.order.productbom.domain.ProductionBomItem;
import com.yserp.project.erp.order.productbom.domain.ProductionBomVo;
import com.yserp.project.erp.order.productbom.mapper.ProductionBomMapper;
import com.yserp.project.erp.order.productbom.service.IProductionBomItemService;
import com.yserp.project.erp.order.productbom.service.IProductionBomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * BOM主Service业务层处理
 *
 * @author yserp
 * @date 2022-08-09
 */
@Service
public class ProductionBomServiceImpl extends ServiceImpl<ProductionBomMapper, ProductionBom> implements IProductionBomService {
    @Resource
    private ProductionBomMapper productionBomMapper;
    @Autowired
    private IProductionBomItemService productionBomItemService;

    /**
     * 查询BOM主
     *
     * @param id BOM主主键
     * @return BOM主
     */
    @Override
    public ProductionBomVo selectProductionBomById(Long id) {
        return ProductionBomVo.builder()
                    .productionBom(productionBomMapper.selectById(id))
                    .items(productionBomItemService.selectProductionBomItemListByMainId(id))
                    .build();
    }

    /**
     * 查询BOM主列表
     *
     * @param productionBom BOM主
     * @return BOM主
     */
    @Override
    public List<ProductionBom> selectProductionBomList(ProductionBom productionBom) {
        QueryWrapper<ProductionBom> queryWrapper = new QueryWrapper<>();
        MybatisPlusUtil.notNullField(productionBom, queryWrapper);
        return productionBomMapper.selectList(queryWrapper);
    }

    /**
     * 新增BOM主
     *
     * @param productionBomDto BOM主
     * @return 结果
     */
    @Override
    @Transactional
    public int insertProductionBom(ProductionBomDto productionBomDto) {
        List<ProductionBomItem> items = productionBomDto.getItems();
        if (CollectionUtils.isEmpty(items)) {
            throw new BusinessException("子表不能为空");
        }
        //验证单号是否存在
        String orderNo = productionBomDto.getBomCode();
        if(StringUtils.isBlank(orderNo)){
            throw new BusinessException("单号不存在");
        }
        Integer count = productionBomMapper.selectCount(new QueryWrapper<ProductionBom>().eq("bom_code", orderNo));
        if(count>0){
            //处理单号，并重新插入缓存
            Integer number = productionBomMapper.selectCount(new QueryWrapper<ProductionBom>().like("bom_code", orderNo.substring(0,orderNo.length()-3)));
            OrderEnums.putCacheOrderNo(orderNo,number);
            throw new BusinessException("单号已存在，请重新下单");
        }else{
            OrderEnums.putCacheOrderNo(orderNo);
        }
        //插入主表
        ProductionBom bom = new ProductionBom();
        BeanUtils.copyBeanProp(bom, productionBomDto);
        int i = productionBomMapper.insert(bom);
        //批量插入子表
        items.stream().forEach(item-> item.setMainId(bom.getId()));
        productionBomItemService.saveBatch(items);
        return i;
    }

    /**
     * 修改BOM主
     *
     * @param productionBomDto BOM主
     * @return 结果
     */
    @Override
    @Transactional
    public int updateProductionBom(ProductionBomDto productionBomDto) {
        List<ProductionBomItem> items = productionBomDto.getItems();
        if(CollectionUtils.isEmpty(items)){
            throw new BusinessException("子表不能为空");
        }
        //修改主表
        ProductionBom bom = new ProductionBom();
        BeanUtils.copyBeanProp(bom, productionBomDto);
        int i = productionBomMapper.updateById(bom);
        //子表
        Long mainId = bom.getId();
        //获取子表
        List<ProductionBomItem> productionBomItems = productionBomItemService.selectProductionBomItemListByMainId(mainId);
        if(!CollectionUtils.isEmpty(productionBomItems)) {
            List<Long> oldIds = productionBomItems.stream().map(ProductionBomItem::getId).collect(Collectors.toList());
            List<Long> newIds = items.stream().map(ProductionBomItem::getId).collect(Collectors.toList());
            oldIds.removeAll(newIds);
            if (!CollectionUtils.isEmpty(oldIds)) {
                productionBomItemService.removeByIds(oldIds);
            }
        }
        for (ProductionBomItem item : items) {
            item.setMainId(mainId);
            productionBomItemService.saveOrUpdate(item);
        }
        return i;
    }

    /**
     * 批量删除BOM主
     *
     * @param ids 需要删除的BOM主主键
     * @return 结果
     */
    @Override
    public int deleteProductionBomByIds(String ids) {
        int result = 0;
        Long[] mainIds = Convert.toLongArray(ids);
        for (Long id : mainIds ) {
            result =deleteProductionBomById(id);
            if(result <= 0){
                break;
            }
        }
        return result;
    }

    /**
     * 删除BOM主信息
     *
     * @param id BOM主主键
     * @return 结果
     */
    @Override
    public int deleteProductionBomById(Long id) {
        int result = 0;
        //更新主表
        int i=productionBomMapper.deleteById(id);
        //更新子表
        //查询子表信息
        List<ProductionBomItem> items = productionBomItemService.selectProductionBomItemListByMainId(id);
        if(!CollectionUtils.isEmpty(items)) {
            List<Long> itemIds = items.stream().map(ProductionBomItem::getId).collect(Collectors.toList());
            boolean b = productionBomItemService.removeByIds(itemIds);
            if (i > 0 && b) {
                result = 1;
            }
        }
        return result;
    }
}
